local wjsl_rule = fk.CreateSkill {
  name = "#wjsl_rule",
}

local EndLessPractice = require "packages/wdtx/EndLessPractice"
local GensLimts = require "packages/wdtx/GensLimts"

--初始化游戏数据
local initGameData = {
  i_layer = 1,--初始关卡
  t_layer = 49,--总关卡
  initgold = 30,--初始金币
  goldpower = 1.7,--获得随机金币*倍率
  maxctiwin = 4,--连胜最多层数即中断当前玩家阶段
  lordslayer = 9,--层主队友+1需要每几层
  lordsperup = 7,--层主队友成长一次需要每几层
  defbossstep = 7,--每过几层对战boss
  laygetskill_n = 5,--层主每过几关获得技能，包括体力上限
  rewd_intval = {{13,1,4},{25,2,5},{35,3,6}}, --关卡选项变化（可以多选与加选）
  layownskills = {mashu = 2,l_wuqian = 14,os_ex__paoxiao = 21,langxi = 25,wjsl_tazhen = 32,liji = 35,df_fengkuang = 38}, --层主关卡技能
  rewards = {gaingold=0.1,skills = 0.12,maxhp = 0.1,lingxin = 0.1,magicbox=0.08,extraslash_num=0.1,angelbless=0.1,slash_dmg_sel=0.08,trick_dmg_sel=0.1,shieldnum = 0.12},--玩家奖励概率配置
  rulename = "#wjsl_rule", --游戏模式名
  godboss = {"godzhangjiao","godsunce","godzhaoyun","godganning","godtaishici","godmachao","godliubei"},--神将boss
  meetpuyuan = {rate = 0.08,meet={3,10}}, --rate是每次概率上升值，meet遇见商店最多次，每几层重置
  initshopskills = 8
}
--初始化游戏数据(单人)
local initGameDataByLess = {
  i_layer = 1,--初始关卡
  t_layer = 42,--总关卡
  initgold = 40,--初始金币
  goldpower = 1.5,--获得随机金币*倍率
  maxctiwin = 4,--连胜最多层数即中断当前玩家阶段
  lordslayer = 60,--层主队友+1需要每几层
  lordsperup = 60,--层主队友成长一次需要每几层
  defbossstep = 7,--每过几层对战boss
  laygetskill_n = 4,--层主每过几关获得技能，包括体力上限
  rewd_intval = {{13,1,4},{25,2,5},{35,3,6}}, --关卡选项变化（可以多选与加选）
  layownskills = {mashu = 2,l_wuqian = 14,os_ex__paoxiao = 21,langxi = 25,wjsl_tazhen = 32,liji = 35,df_fengkuang = 38}, --层主关卡技能
  rewards = {gaingold=0.1,skills = 0.12,maxhp = 0.1,lingxin = 0.1,magicbox=0.08,extraslash_num=0.1,angelbless=0.1,slash_dmg_sel=0.08,trick_dmg_sel=0.1,shieldnum = 0.12},--玩家奖励概率配置
  rulename = "#wjsl_rule", --游戏模式名
  godboss = {"godzhangjiao","godsunce","godzhaoyun","godganning","godtaishici","godmachao","godliubei"},--神将boss
  meetpuyuan = {rate = 0.07,meet={2,10}}, --rate是每次概率上升值，meet遇见商店最多次，每几层重置
  initshopskills = 8
}

wjsl_rule:addEffect(fk.GameStart, {
  priority = 0.001,
  can_refresh = function(self, event, target, player, data)
    return player.id < 0 and player.role == "lord"
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local logic = player.room.logic
    local endlPrac = logic.endlPrac
    local all_generals = {}
    local clone_generals = {}
    local whitegens = GensLimts:getToTalGens()
    for _, gen in ipairs(whitegens) do
      local g = Fk.generals[gen]
      if g then
        table.insert(all_generals, g.name)
        table.insert(clone_generals,g.name)
      end
    end
    endlPrac.all_generals = all_generals
    endlPrac.clone_generals = clone_generals

    local allgenerals = endlPrac.all_generals
    local otherplayers = endlPrac:getOPlayers(player)
    local humans,lordloyas = 0,0
    for _, pr in ipairs(room.players) do
      if pr.id > 0 then
        humans = humans + 1
      else
        if pr.role ~= "rebel" then
          lordloyas = lordloyas + 1
        end
      end
    end
    --规则限制
    -- if not IStest then
    if not endlPrac or #allgenerals == 0 then
      room:doBroadcastNotify("ShowToast", "模式或者人机无将池错误")
      room:gameOver(player.role)
      return
    end
    if #room.players ~= 2 then
      if humans > 3 or lordloyas / humans <= 1 then
        room:doBroadcastNotify("ShowToast", "玩家数量过多不符合游戏规则")
        room:gameOver(player.role)
        return
      end
    else
      if humans ~= 1 then
        room:doBroadcastNotify("ShowToast", "玩家数量不符合游戏规则")
        room:gameOver(player.role)
        return
      end
    end
    -- end
    local introduces = {"justsoso","justbored","justlike"}
    table.shuffle(introduces)
    for _, p in ipairs(room.players) do
      if p.id > 0 then
        local reply = room:askToCustomDialog(p,{
          skill_name = wjsl_rule.name,
          qml_path = "packages/wdtx/qml/DialogChoiceBox.qml",
          extra_data = {"author_says","dfst_introduce", introduces, "hxfc_author"}
        })
        if reply == "justsoso" then
          room:doBroadcastNotify("ShowToast", "幻想风车：看来我还需要考虑其他模式.....")
          room:addPlayerMark(p,"@slash_num",1)
        elseif reply == "justlike" then
          room:doBroadcastNotify("ShowToast", Fk:translate(p.general).."承蒙喜欢❤")
          room:addPlayerMark(p,"@slash_num",2)
        end
      else
        if p.role ~= "lord" then
          if humans - 1 > 0 and p.role == "loyalist" then
            humans = humans - 1
            endlPrac:changeGeneral(p)
          else
            if p.role == "rebel" then
              room:handleAddLoseSkills(p, "wjsl_zhenfen", nil, false)
            end
            -- if not IStest then
            room:killPlayer({ who = p })
            -- end
          end
        end
      end
    end
    local gamedata = #room.players ~= 2 and table.clone(initGameData) or table.clone(initGameDataByLess)
    endlPrac:initData(player, gamedata)
    endlPrac:layerRewards()
  end,
})
--保留玩家本模式重要的标记
local SAVEmarks = {"curlayerphase","@slash_dmg","@trick_dmg","@pdlbox","@gold_num","@df_lingxin","@shieldnum","@slash_num"}

wjsl_rule:addEffect(fk.BuryVictim, {
  priority = 0.001,
  can_refresh = function(self, event, target, player, data)
    return player.id < 0 and player.role == "lord"
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:setTag("SkipGameRule", true)
    local body = data.who
    local logic = room.logic
    local endlPrac = logic.endlPrac
    local allgenerals = endlPrac.all_generals
    local e = room.logic:getCurrentEvent():findParent(GameEvent.Turn)
    if not target.dead or not e then return end
    if not allgenerals or #allgenerals == 0 then
      room:doBroadcastNotify("ShowToast", "将池耗尽")
      room:gameOver("rebel")
      return
    end
    --过了所有关卡胜利
    local curlayer = endlPrac:getLayer()
    --层主及队友都死亡
    --层主忠臣队友阵亡处理
    if body.role ~= "rebel" then
      endlPrac:bury(body)
      local lords = table.filter(room.alive_players,function(pr) return pr.id < 0 and GensLimts:isSameCamp(body,pr) end)
      if #lords > 0 then
        local draw = 2 + math.floor(curlayer / 10)
        endlPrac:drawCardsByCamp(draw,lords)
        if body.role ~= "lord" then return end
      end
    else
      --玩家阵亡处理
      if body.role == "rebel" then
        --守护天使效果
        if body:getMark("@@guardangle") > 0 then
          endlPrac:bury(body,SAVEmarks)
          room:revivePlayer(body, false)
          room:drawCards(body, 4 + (math.floor(curlayer/10) * 2),wjsl_rule.name)
          if room.current.role ~= body.role then
            endlPrac:endWhoPhase()
          end
          return
        end
        --全部阵亡结算
        local alivehumans = endlPrac:getAliveHumans()
        if #alivehumans <= 0 then
          room:doBroadcastNotify("ShowToast", "玩家全部阵亡，游戏结束。爬塔层数"..curlayer)
          room:gameOver("lord")
          return
        end
        --玩家阵亡处理
        endlPrac:bury(body,SAVEmarks)
        endlPrac:otherPlayersDraw(2+(math.floor(curlayer/10)*2))
        room:doBroadcastNotify("ShowToast", Fk:translate(body.general) .."阵亡，别放弃还有机会复活")
        return
      end
    end
    if curlayer >= endlPrac.totallayer then
      room:doBroadcastNotify("ShowToast", endlPrac.totallayer.."层！恭喜你爬到塔顶之巅。")
      room:gameOver("rebel")
      return
    end
    ----------------------------执行下一层逻辑--------------------------
    --boss死亡后获得其中一个技能
    local defeat
    if data.damage and data.damage.from and not data.damage.from.dead then
      defeat = data.damage.from
    else
      defeat = data.killer or room.alive_players[1]
    end
    body = endlPrac:getLayerOwner()
    local otherplayers = endlPrac:getOPlayers(body)
    local lords = {}
    local rebels = -1
    for _,pr in ipairs(room.players) do
      if pr.id < 0 and GensLimts:isSameCamp(body,pr) and body.id ~= pr.id then table.insert(lords,pr) end
      if pr.id > 0 then rebels = rebels + 1 end
    end
    --复活层主队友或者其或者升级maxhp、技能数
    local extrafriend = endlPrac:getExtraFriendByLayers()
    local relifenum = math.floor((curlayer + 1) / extrafriend) + rebels
    if #lords > 0 and relifenum > 0 then
      endlPrac:reLayerFriends(lords,math.min(relifenum,4))
    end
    --层主死亡层数+1并复活加强
    endlPrac:removeLayerBoss(defeat)
    endlPrac:changeLayer(1)
    --清除相关技能
    endlPrac:removeRelateSkills(body)
    --转变武将且复活
    local layer = endlPrac:getLayer()
    local haveboss = endlPrac:getLayerBoss()
    local newgeneral = endlPrac:changeGeneral(body,haveboss)
    if not newgeneral then
      room:doBroadcastNotify("ShowToast", "将池耗尽")
      room:gameOver("rebel")
      return
    end
    --删除复活前技能
    endlPrac:removeOldSkills(newgeneral,body)
    --刷新最大maxhp与hp
    local cal_add = math.floor(layer / endlPrac:getLayerSkillnum())
    if haveboss then
      cal_add = math.floor(cal_add * 2.5)
    end
    if cal_add > 0 then
      endlPrac:updateMax(body,cal_add)
    end
    --获得关卡技能
    endlPrac:getLaySkills(body)
    --层主或层队友每过n关获得随机技能
    local n = endlPrac:getRskiNum()
    if n > 0 then
      endlPrac:getRandSkills(n,body)
    end
    --刷新层数
    endlPrac:updateLayer(body,"@wj_layer")
    --通知其他角色层数
    endlPrac:notifyLayer("curlayerphase")
    --摸等量手牌
    endlPrac:drawByRelife(body)
    --------------------------------------------------------------------
    -----------------------玩家处理--------------------------------------
    --------------------------------------------------------------------
    if rebels > 0 and math.floor((curlayer + 1) / extrafriend) > math.floor(curlayer / extrafriend) and relifenum <= 4 and rebels + 1 ~= 3 then
      endlPrac:relifeAIRebels()
    end
    endlPrac:gainRandGold()
    endlPrac:meetPuYuan()
    endlPrac:addContiWin(1)
    --每3+（层数/10）关获得一次奖励
    local step = math.floor(layer / 10)
    local step_n = layer % 10
    local cal_step = step_n % (3 + step)
    if cal_step ~= 0 then
      --连胜超过一定回合结束当前阶段
      endlPrac:handleContiWin()
      return
    end
    --玩家潘多拉技能重置
    endlPrac:resetPdlSkills()
    --随机的奖励选项
    --开始选择
    endlPrac:layerRewards()
    --召唤潘多拉
    -- local call_n = 6 * #otherplayers
    -- endlPrac:callPanduola(body,call_n)
    --连胜超过一定回合结束当前阶段
    endlPrac:handleContiWin()
  end,
})

wjsl_rule:addEffect(fk.GameOverJudge, {
  priority = 0.001,
  can_refresh = function(self, event, target, player, data)
    return player.id < 0 and player.role == "lord"
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:setTag("SkipGameRule", true)
  end,
})

wjsl_rule:addEffect(fk.TurnStart, {
  priority = 0.001,
  can_refresh = function(self, event, target, player, data)
    return player == target
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local endlPrac = room.logic.endlPrac
    if endlPrac then
      endlPrac:setContiWin(0)
    end
  end,
})
wjsl_rule:addEffect(fk.DrawNCards, {
  priority = 0.001,
  can_refresh = function(self, event, target, player, data)
    return player.id < 0 and player.role == "lord"
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local endlPrac = room.logic.endlPrac
    local haveboss = endlPrac:getLayerBoss()
    if haveboss then
      local layer = endlPrac:getLayer()
      local value = math.ceil(layer / 10) * 2
      data.n = data.n + value
    end
  end,
})


return wjsl_rule